package org.fhawk.tinyspring.ioc;

import org.fhawk.tinyspring.core.ClassHelper;
import org.fhawk.tinyspring.core.error.InitializationError;
import org.fhawk.tinyspring.ioc.annotation.BaseBean;
import org.fhawk.tinyspring.util.AnnotationUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by tuo on 8/17/2016.
 */
@SuppressWarnings("unchecked")
public class BeanHelper {
    private static final ConcurrentHashMap<Class<?>, Object> beanMap = new ConcurrentHashMap<>();
    private static Logger logger = LoggerFactory.getLogger(BeanHelper.class);

    private BeanHelper() {
    }

    static {
        //获取基础包中所有的类
        List<Class<?>> classList = ClassHelper.getBasePackageClassList();
        //判断类是否有BaseBean注解，有注解的进行实例化并且放入到容器beanMap中
        classList.stream().filter(clazz -> AnnotationUtil.isAnnotationPresent(clazz, BaseBean.class) && !clazz.isAnnotation()).forEach(clazz -> {
            logger.info("初始化Bean:{} 并放入容器。", clazz.getName());
            try {
                Object instance = clazz.newInstance();
                beanMap.put(clazz, instance);
            } catch (Exception e) {
                logger.error("初始化Bean:{} 失败", clazz.getName(), e);
                throw new InitializationError("初始化 BeanHelper 出错！", e);
            }
        });
    }

    static ConcurrentHashMap<Class<?>, Object> getBeanMap() {
        return beanMap;
    }

    public static <T> T getBean(Class<T> clazz) {
        if (!beanMap.containsKey(clazz)) {
            logger.error("Bean:{}实例不存在", clazz.getName());
        }
        return (T) beanMap.get(clazz);
    }

    public static void setBean(Class<?> clazz, Object instance) {
        beanMap.put(clazz, instance);
    }


}
